package repository

import (
	"buding-ai/internal/core"
	"buding-ai/internal/repository/model"
	"buding-ai/pkg/utils/paginate"
	"sync"
)

var (
	mcpRepos *McpRepository
	mcpOnce  sync.Once
)

type McpRepository struct {
	// 删除db字段，统一使用全局core.DB
}

func GetMcpRepository() *McpRepository {
	mcpOnce.Do(func() {
		mcpRepos = &McpRepository{}
	})
	return mcpRepos
}

// GetTools 获取所有可用工具
func (r *McpRepository) GetTools() ([]model.Mcp, error) {
	var list []model.Mcp
	if tx := core.DB.Model(&model.Mcp{}).Where("status=?", 1).Find(&list); tx.Error != nil {
		return nil, tx.Error
	}
	return list, nil
}

// GetById 根据ID获取MCP
func (r *McpRepository) GetById(id uint64) (*model.Mcp, error) {
	var mcp model.Mcp
	if err := core.DB.First(&mcp, id).Error; err != nil {
		return nil, err
	}
	return &mcp, nil
}

// CheckNameExists 检查名称是否已存在
func (r *McpRepository) CheckNameExists(name string) (bool, error) {
	var count int64
	if err := core.DB.Model(&model.Mcp{}).Where("name = ?", name).Count(&count).Error; err != nil {
		return false, err
	}
	return count > 0, nil
}

// CheckNameExistsExcept 检查名称是否被其他MCP使用
func (r *McpRepository) CheckNameExistsExcept(name string, id uint64) (bool, error) {
	var count int64
	if err := core.DB.Model(&model.Mcp{}).Where("name = ? AND id != ?", name, id).Count(&count).Error; err != nil {
		return false, err
	}
	return count > 0, nil
}

// CreateMcp 创建MCP
func (r *McpRepository) CreateMcp(mcp *model.Mcp) error {
	return core.DB.Create(mcp).Error
}

// UpdateMcp 更新MCP信息
func (r *McpRepository) UpdateMcp(id uint64, updates map[string]interface{}) error {
	return core.DB.Model(&model.Mcp{}).Where("id = ?", id).Updates(updates).Error
}

// DeleteMcp 删除MCP
func (r *McpRepository) DeleteMcp(id uint64) error {
	return core.DB.Where("id = ?", id).Delete(&model.Mcp{}).Error
}

// GetMcpPage 分页获取MCP列表
func (r *McpRepository) GetMcpPage(pageRequest paginate.PageRequest) (*paginate.PageResponse, error) {
	query := core.DB.Model(&model.Mcp{})

	// 如果有搜索关键词，添加模糊查询条件
	if pageRequest.Keyword != "" {
		searchTerm := "%" + pageRequest.Keyword + "%"
		query = query.Where("name LIKE ? OR describe LIKE ?",
			searchTerm, searchTerm)
	}

	// 执行分页查询
	var mcps []model.Mcp
	pageResult, err := paginate.Paginator(query, pageRequest.Page, pageRequest.PageSize, pageRequest.Sort, pageRequest.Order, &mcps)

	if err != nil {
		return nil, err
	}

	return &pageResult, nil
}

func (r *McpRepository) GetUserPage(request paginate.PageRequest) (*paginate.PageResponse, error) {
	query := core.DB.Model(&model.Mcp{})

	// 如果有搜索关键词，添加模糊查询条件
	if request.Keyword != "" {
		searchTerm := "%" + request.Keyword + "%"
		query = query.Where("`name` LIKE ? OR `describe` LIKE ?",
			searchTerm, searchTerm)
	}
	// 执行分页查询
	var mcps []model.Mcp
	pageResult, err := paginate.Paginator(query, request.Page, request.PageSize, request.Sort, request.Order, &mcps)

	if err != nil {
		return nil, err
	}
	return &pageResult, nil
}
